import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {Input} from "antd";

interface FIleNameInputProps {
    ds: any,
    value: string,
    disabled?: boolean,
    comProps?: any,
    onChange: Function,
}

const FIleNameInput: FC<FIleNameInputProps> = (props) => {

    const suffixRef = useRef("");
    const [value, setValue] = useState<any>();

    useEffect(() => {
        const {ds = {}}: { ds?: any } = props;
        let newValue: any = ds.value || props.value;
        if (newValue && newValue.indexOf(".") !== -1) {
            suffixRef.current = newValue.split(".")[1];
            newValue = newValue.split(".")[0];
        }
        setValue(newValue);
    }, [props.ds]);

    const handleChange: Function = useCallback((e: e) => {
        setValue(e.target.value);
        props.onChange && props.onChange(e.target.value + (suffixRef.current ? ("." + suffixRef.current) : ""));
    }, [props.onChange]);

    const renderFIleNameInput = useMemo(() => {
        let {disabled, comProps = {}}: { disabled: boolean, comProps: any } = props;
        let inputProps: any = {
            ...comProps,
            value,
            disabled,
            onChange: handleChange
        }
        if (suffixRef.current) {
            inputProps.addonAfter = "." + suffixRef.current;
        }
        return (
            <Input {...inputProps}/>
        )
    }, [value, props]);

    return (renderFIleNameInput);
};
export default React.memo(FIleNameInput);